﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils;

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BW.Mes.WinForms.Common;

namespace BW.Mes.WinForms.Process.Aduit
{
    public partial class WaitAduitForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";

        public WaitAduitForm()
        {
            InitializeComponent();

            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 绑定事件
            this.Load += WaitAduitForm_Load;
            this.checkButton1.Click += CheckButton1_Click;
            
            // 添加审批按钮
            SimpleButton approveButton = new SimpleButton();
            approveButton.Text = "审批";
            approveButton.Name = "approveButton";
            approveButton.Location = new Point(checkButton1.Location.X + checkButton1.Width + 10, checkButton1.Location.Y);
            approveButton.Size = checkButton1.Size;
            approveButton.Click += ApproveButton_Click;
            this.Controls.Add(approveButton);
            
            // 设置表格属性
            SetupGridView();
        }

        private void SetupGridView()
        {
            // 配置GridView的基本属性
            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            
            // 清除所有列，然后按照我们想要的顺序重新添加
            gridView1.Columns.Clear();
            
            // 首先添加复选框列
            DevExpress.XtraGrid.Columns.GridColumn checkColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            checkColumn.Caption = "选择";
            checkColumn.FieldName = "Ischeck";
            checkColumn.Name = "gridColumnCheck";
            checkColumn.Visible = true;
            checkColumn.VisibleIndex = 0; // 明确设置为第一列
            checkColumn.Width = 40;
            checkColumn.OptionsColumn.AllowEdit = true;
            checkColumn.OptionsColumn.FixedWidth = true;
            
            // 设置复选框编辑器
            DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit repositoryItemCheckEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
            gridControl1.RepositoryItems.Add(repositoryItemCheckEdit);
            checkColumn.ColumnEdit = repositoryItemCheckEdit;
            
            // 添加到列集合
            gridView1.Columns.Add(checkColumn);
            
            // 定义所有需要的列并按顺序添加
            var columns = new List<DevExpress.XtraGrid.Columns.GridColumn>();
            
            // WorkflowId列
            var workIdColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            workIdColumn.Caption = "唯一标识符";
            workIdColumn.FieldName = "WorkflowId";
            workIdColumn.Name = "workid";
            workIdColumn.Visible = true;
            workIdColumn.VisibleIndex = 1;
            workIdColumn.Width = 94;
            columns.Add(workIdColumn);
            
            // StepId列
            var stepIdColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            stepIdColumn.Caption = "步骤id";
            stepIdColumn.FieldName = "StepId";
            stepIdColumn.Name = "stepid";
            stepIdColumn.Visible = true;
            stepIdColumn.VisibleIndex = 2;
            stepIdColumn.Width = 94;
            columns.Add(stepIdColumn);
            
            // StepName列
            var stepNameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            stepNameColumn.Caption = "步骤名称";
            stepNameColumn.FieldName = "StepName";
            stepNameColumn.Name = "stepname";
            stepNameColumn.Visible = true;
            stepNameColumn.VisibleIndex = 3;
            stepNameColumn.Width = 94;
            columns.Add(stepNameColumn);
            
            // AuditUserId列
            var auditUserIdColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            auditUserIdColumn.Caption = "审批人id";
            auditUserIdColumn.FieldName = "AuditUserId";
            auditUserIdColumn.Name = "audituserid";
            auditUserIdColumn.Visible = true;
            auditUserIdColumn.VisibleIndex = 4;
            auditUserIdColumn.Width = 94;
            columns.Add(auditUserIdColumn);
            
            // AuditUserName列
            var auditUserNameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            auditUserNameColumn.Caption = "审批人名称";
            auditUserNameColumn.FieldName = "AuditUserName";
            auditUserNameColumn.Name = "auditusername";
            auditUserNameColumn.Visible = true;
            auditUserNameColumn.VisibleIndex = 5;
            auditUserNameColumn.Width = 94;
            columns.Add(auditUserNameColumn);
            
            // Status列
            var statesColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            statesColumn.Caption = "状态";
            statesColumn.FieldName = "Status";
            statesColumn.Name = "states";
            statesColumn.Visible = true;
            statesColumn.VisibleIndex = 6;
            statesColumn.Width = 94;
            columns.Add(statesColumn);
            
            // Remark列
            var remarkColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            remarkColumn.Caption = "意见";
            remarkColumn.FieldName = "Remark";
            remarkColumn.Name = "reamk";
            remarkColumn.Visible = true;
            remarkColumn.VisibleIndex = 7;
            remarkColumn.Width = 94;
            columns.Add(remarkColumn);
            
            // ExecutionPointer列
            var executionPointerColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            executionPointerColumn.Caption = "节点";
            executionPointerColumn.FieldName = "ExecutionPointer";
            executionPointerColumn.Name = "executionPointer";
            executionPointerColumn.Visible = true;
            executionPointerColumn.VisibleIndex = 8;
            executionPointerColumn.Width = 94;
            columns.Add(executionPointerColumn);
            
            // AuditType列
            var auditTypeColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            auditTypeColumn.Caption = "操作类型";
            auditTypeColumn.FieldName = "AuditType";
            auditTypeColumn.Name = "audittype";
            auditTypeColumn.Visible = true;
            auditTypeColumn.VisibleIndex = 9;
            auditTypeColumn.Width = 94;
            columns.Add(auditTypeColumn);
            
            // 将所有列添加到GridView
            foreach (var column in columns)
            {
                gridView1.Columns.Add(column);
            }
            
            // 设置点击事件，用于处理复选框点击
            gridView1.Click += GridView1_Click;
            
            // 添加鼠标按下事件，用于实现列标题点击全选功能
            gridView1.MouseDown += GridView1_MouseDown;
        }

        private void WaitAduitForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 加载数据
                LoadAuditData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CheckButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取搜索条件
                string workflowId = textEdit1.Text.Trim();
                string stepName = textEdit2.Text.Trim();
                
                // 构建查询URL
                string url = $"{_apiBaseUrl}/T5/OperationModel/ShowAuditDataClick?PagIndex=1&PagSize=7";
                
                // 添加工作流ID参数
                if (!string.IsNullOrEmpty(workflowId))
                {
                    url += $"&WorkflowId={Uri.EscapeDataString(workflowId)}";
                }
                
                // 添加步骤名称参数
                if (!string.IsNullOrEmpty(stepName))
                {
                    url += $"&StepName={Uri.EscapeDataString(stepName)}";
                }
                
                // 获取当前登录用户名
                string auditUserName = GetCurrentUserName();
                url += $"&AuditUserName={Uri.EscapeDataString(auditUserName)}";
                
                // 执行查询
                GetAuditDataAsync(url);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        


        private void LoadAuditData()
        {
            try
            {
                // 显示加载中提示
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL
                string url = $"{_apiBaseUrl}/T5/OperationModel/ShowAuditDataClick?PagIndex=1&PagSize=7";
                
                // 获取当前登录用户名
                string auditUserName = GetCurrentUserName();
                url += $"&AuditUserName={Uri.EscapeDataString(auditUserName)}";
                
                Console.WriteLine($"API请求URL: {url}");
                
                // 发起API请求
                GetAuditDataAsync(url);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 获取当前登录用户名
        /// </summary>
        /// <returns>登录用户名</returns>
        private string GetCurrentUserName()
        {
            // 优先使用用户输入的用户名
            if (!string.IsNullOrEmpty(RequestUser.InputUserName))
            {
                return RequestUser.InputUserName;
            }
            // 如果没有输入的用户名，则使用API返回的用户名
            else if (RequestUser.CurrentUser != null && !string.IsNullOrEmpty(RequestUser.CurrentUser.UserName))
            {
                return RequestUser.CurrentUser.UserName;
            }
            // 如果都没有，返回默认值
            else
            {
                return "吴不凡"; // 默认用户名
            }
        }

        private async void GetAuditDataAsync(string url)
        {
            try
            {
                // 发送HTTP请求
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                // 获取响应内容
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"API响应: {content}");

                // 反序列化响应数据
                var apiResult = JsonConvert.DeserializeObject<ApiResult<List<AuditProcessModel>>>(content);

                if (apiResult != null && apiResult.success == 200 && apiResult.pagingdata != null)
                {
                    // 确保每行都有正确初始化的Ischeck属性
                    foreach (var item in apiResult.pagingdata)
                    {
                        item.Ischeck = false;
                    }
                    
                    // 绑定数据到GridControl
                    gridControl1.DataSource = apiResult.pagingdata;
                    
                    // 刷新GridView
                    gridControl1.RefreshDataSource();
                    gridView1.RefreshData();
                    gridView1.BestFitColumns();

                    Console.WriteLine($"已加载 {apiResult.pagingdata.Count} 条记录");
                }
                else
                {
                    // 处理API返回错误
                    string errorMessage = apiResult != null ? apiResult.message : "未知错误";
                    XtraMessageBox.Show($"获取数据失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                    // 清空数据源
                    gridControl1.DataSource = null;
                }
            }
            catch (HttpRequestException httpEx)
            {
                XtraMessageBox.Show($"HTTP请求错误: {httpEx.Message}\n请确认API服务是否启动并可访问。", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        private void GridView1_Click(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo hitInfo = view.CalcHitInfo(view.GridControl.PointToClient(Control.MousePosition));
            
            if (hitInfo.InRowCell && hitInfo.Column != null && hitInfo.Column.FieldName == "Ischeck")
            {
                // 如果点击了复选框单元格
                var dataRow = view.GetRow(hitInfo.RowHandle) as AuditProcessModel;
                if (dataRow != null)
                {
                    // 切换复选框状态
                    dataRow.Ischeck = !dataRow.Ischeck;
                    // 刷新单元格
                    view.RefreshRow(hitInfo.RowHandle);
                }
            }
        }

        private void GridView1_MouseDown(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

            // 使用正确的方式检查是否点击了列标题
            if (hitInfo.InColumn && hitInfo.Column != null && hitInfo.Column.FieldName == "Ischeck")
            {
                // 如果点击了复选框列的列头
                var dataSource = gridControl1.DataSource as List<AuditProcessModel>;
                if (dataSource == null || dataSource.Count == 0) return;

                // 检查当前状态，如果所有行都选中，则取消全选；否则全选
                bool allChecked = dataSource.All(item => item.Ischeck);
                
                // 执行全选或取消全选
                foreach (var item in dataSource)
                {
                    item.Ischeck = !allChecked;
                }
                
                // 刷新表格显示
                gridControl1.RefreshDataSource();
                gridView1.RefreshData();
            }
        }

        // 审批按钮点击事件处理
        private void Auditbutton_CheckedChanged (object sender, EventArgs e)
        {
            // 获取选中的行
            var selectedRows = GetSelectedRows();
            
            if (selectedRows.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一条数据进行审批", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            if (selectedRows.Count > 1)
            {
                XtraMessageBox.Show("一次只能审批一条数据，请只选择一条数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            // 获取选中行的WorkflowId
            var selectedRow = selectedRows[0];
            string workflowId = selectedRow.WorkflowId;
            
            if (string.IsNullOrEmpty(workflowId))
            {
                XtraMessageBox.Show("选中的数据缺少工作流ID，无法进行审批", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            // 创建并显示审批表单，传递WorkflowId
            using (var auditForm = new AuditForm(workflowId))
            {
                auditForm.ShowDialog(this);
                
                // 如果需要在审批完成后刷新数据
                if (auditForm.DialogResult == DialogResult.OK)
                {
                    LoadAuditData();
                }
            }
        }
        
        // 获取选中的行
        private List<AuditProcessModel> GetSelectedRows()
        {
            List<AuditProcessModel> selectedRows = new List<AuditProcessModel>();
            
            if (gridControl1.DataSource is List<AuditProcessModel> dataSource)
            {
                foreach (var item in dataSource)
                {
                    if (item.Ischeck)
                    {
                        selectedRows.Add(item);
                    }
                }
            }
            
            return selectedRows;
        }

        private void ApproveButton_Click(object sender, EventArgs e)
        {

        }
    }

    // API结果封装类
    public class ApiResult<T>
    {
        /// <summary>
        /// 总数
        /// </summary>
        public int totalCount { get; set; }
        /// <summary>
        /// 状态码
        /// </summary>
        public int success { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public T pagingdata { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string message { get; set; }
    }

    // 审核流程数据模型
    public class AuditProcessModel
    {
        public bool Ischeck { get; set; }
        public long Id { get; set; }
        public string WorkflowId { get; set; }
        public string StepId { get; set; }
        public string StepName { get; set; }
        public long AuditUserId { get; set; }
        public string AuditUserName { get; set; }
        public string Status { get; set; }
        public string Remark { get; set; }
        /// <summary>
        /// 操作节点
        /// </summary>
        public string ExecutionPointer { get; set; }
        /// <summary>
        /// 操作类型
        /// </summary>
        public string AuditType { get; set; }
    }
}